<template>
  <div class="treeselect" style="width: 100%">
    <TreeSelect placeholder="请选择" :tree-data="treeData" v-model:value="treeDataValue" :fieldNames="fieldNames"
      :size="size" :allowClear="isAllowClears" :multiple="multiple" :tree-checkable="treeCheckable" style="width: 100%">
      <template #title="scope" v-if="type === 'org'">
        <div class="title_tree">
          <span>{{ scope.name }}</span>
          <a-tag color="blue" v-if="scope.typeName && showTag"> {{ scope.typeName }}</a-tag>
        </div>
      </template>
    </TreeSelect>
  </div>
</template>

<script lang="ts">
import { ref, defineComponent, computed, watch } from 'vue';

import { TreeSelect } from 'ant-design-vue';

import { defHttp } from '@/utils/http/axios';

enum ApiUrls {
  org = 'Organizations/TreeAllByLogin', //机构
  memberGroup = 'BinderGroup',
  memberGroups = 'BinderGroup/Select',
  personType = '/key-values/EnableTrees',
  personList = '/key-values/Trees/BINDER_TYPE',
  personTypePatrol = '/BizPatrolGroup/MemerType',
  EnableTrees = "/key-values/EnableTrees"
}



export default defineComponent({
  name: 'treeSelect',
  components: { TreeSelect },
  props: {
    isAllowClears: {
      type: Boolean,
      default: true,
    },
    type: {
      type: String,
      default: 'org',
    },
    showTag: {
      type: Boolean,
      default: true,
    },
    treeCheckable: {
      type: Boolean,
      default: false,
    },
    isFirst: {
      type: Boolean,
      default: false,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    value: {
      type: String,
      default: '',
    },
    code: {
      type: String,
      default: '',
    },
    xhrParams: {
      type: Object,
      default: () => {
        return {};
      },
    },
    httpUrl: {
      type: String,
      default: '',
    },
    size: {
      type: String,
      default: '',
    },
    parentId: {
      type: String,
      default: '0',
    },
    watchParams: {
      type: String || Array,
      default: '',
    },
    fieldNames: {
      type: Object,
      default: () => {
        return {
          label: 'name',
          value: 'id',
          children: 'children',
        };
      },
    },
    unshiftOptions: {
      type: Object,
      default: () => {
        return [];
      },
    },
  },
  setup(props, context) {
    let {
      type,
      xhrParams,
      unshiftOptions,
      watchParams,
      fieldNames,
      multiple,
      httpUrl,
      parentId,
      size,
      treeCheckable,
      isFirst,
      showTag,
      code,
    } = props;
    if (type === "EnableTrees") {
      fieldNames = {
        label: 'name',
        value: 'code',
        children: 'children',
      }
    }
    const newValue: any = ref(props.value);
    watch(
      () => props.value,
      (n: any) => {
        if (n instanceof Array) {
          newValue.value = n;
        } else if (multiple && !n) {
          newValue.value = [];
        }
        else if (n) {
          newValue.value = n + '';
        } else {
          newValue.value = ' ';
        }
      },
    );

    watch(
      () => props.parentId,
      (n) => {
        parentId = n;
        getData(type);
      },
    );

    if (watchParams) {
      //当进行多个监听的时候只监听这个对象，不监听所有的key
      if (Array.isArray(watchParams)) {
        // watchParams.forEach((item: any) => {
        watch(
          () => props.xhrParams,
          (n) => {
            xhrParams = n;
            getData(type);
          },
          {
            deep: true,
          },
        );
        // });
      } else {
        watch(
          () => props.xhrParams[watchParams],
          (n) => {
            if (n) {
              xhrParams[watchParams] = n;
              getData(type);
            }
          },
          {
            deep: true,
          },
        );
      }
    }

    const treeDataValue = computed({
      get: () => {
        if (!newValue.value) return;
        return newValue.value;
      },
      set: (v) => {
        context.emit('change', v);
        context.emit('customChange', v);
        newValue.value = v;
      },
    });

    // const changes = (value) => {
    //   value = value.filter((x) => x);
    //   if (treeCheckable) {
    //     context.emit('change', value, '123');
    //   } else {
    //     let itemData = treeData.value.find((item) => {
    //       return item.id === value;
    //     });
    //     context.emit('change', value, itemData.name);
    //   }
    //   treeDataValue.value = value;
    // };

    const treeData = ref([]);

    const getData = (type) => {
      let url = httpUrl || ApiUrls[type];
      parentId = type == 'org' ? '' : parentId;
      if (type === "EnableTrees") {
        xhrParams.parentCode = code
      }
      defHttp
        .get({ url: url + httpUrl ?? `${parentId ? `/${parentId}` : ''}`, params: xhrParams })
        .then((res) => {
          if (xhrParams.data == 'entities') {
            formatList(res.data.entities);
          } else {
            formatList(res.data);
          }
          if (isFirst) {
            let v = treeData.value[0]?.id;
            treeDataValue.value = v;
            context.emit('change', v);
          }

          context.emit('loadList', treeData.value);
        });
    };

    getData(type);

    const formatList = (list) => {
      if (unshiftOptions.length) {
        list.unshift(...unshiftOptions);
      }
      treeData.value = list;
    };

    return {
      treeData,
      treeDataValue,
      fieldNames,
      size,
      type,
      showTag,
      treeCheckable,
    };
  },
});
</script>

<style lang="less">
.title_tree {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 100%;
}

.ant-select-tree-treenode {
  width: 100%;
}
</style>
